#!/bin/bash
##第一个 输出到的文件名称
##第二个 通道名
FILE_NAME=$1
STR=`sed -n '1p' ./${FILE_NAME}`
TEMP_STR=($STR)
BLOCKCHAIN_NAME=${TEMP_STR[1]}
CHANNEL_NAME=$2
STR=`sed -n '4p' ./${FILE_NAME}`
TEMP_STR=($STR)
ORDERER_COUNT=${TEMP_STR[1]}

# echo ${FILE_NAME}
# echo ${BLOCKCHAIN_NAME}
# echo ${CHANNEL_NAME}
# echo ${ORDERER_COUNT}
## tail -n1 显示最后一行
function createChannel(){
  line=`sed -n '/organizations:/=' ${FILE_NAME} | tail -n1`
  line=`expr ${line} - 1`
  echo "  ${CHANNEL_NAME}: #${CHANNEL_NAME}
    # Required. list of orderers designated by the application to use for transactions on this
    # channel. This list can be a result of access control (\"org1\" can only access \"ordererA\"), or
    # operational decisions to share loads from applications among the orderers.  The values must
    # be \"names\" of orgs defined under \"organizations/peers\"
    # deprecated: not recommended, to override any orderer configuration items, entity matchers should be used.
    #    orderers:
    #      - orderer.example.com

    # 不要缺少当前channel的orderer节点
    orderers: #${CHANNEL_NAME}" > temp.txt
    for(( i=0;i<`expr ${ORDERER_COUNT} + 0`;i++));do
    echo "      - orderer${i}" >> temp.txt
  	done
  	echo "    # Required. list of peers from participating orgs
    policies: #${CHANNEL_NAME}
      #[Optional] options for retrieving channel configuration blocks
      queryChannelConfig:
        #[Optional] min number of success responses (from targets/peers)
        minResponses: 1
        #[Optional] channel config will be retrieved for these number of random targets
        maxTargets: 1
        #[Optional] retry options for query config block
        retryOpts:
          #[Optional] number of retry attempts
          attempts: 5
          #[Optional] the back off interval for the first retry attempt
          initialBackoff: 500ms
          #[Optional] the maximum back off interval for any retry attempt
          maxBackoff: 5s
          #[Optional] he factor by which the initial back off period is exponentially incremented
          backoffFactor: 2.0
    peers:  #${CHANNEL_NAME}" >> temp.txt

  #sed -i '2 r temp.txt' hosts.txt
  
  sed -i "${line} r temp.txt" ${FILE_NAME}
  rm temp.txt
}


createChannel


